import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:riverpod_t/base/refresh_header.dart';
import 'loadiing_footer.dart';

typedef ItemWidgetBuilder<T> = Widget Function(T item, int index);
typedef IndexedItemBuilder<T> = Widget Function(T item, {required int index});

class BaseListView<T> extends StatefulWidget {
  final bool enablePullUp;
  final bool enablePullDown;
  final VoidCallback? onRefresh;
  final VoidCallback? onLoading;
  final RefreshController? refreshController;
  final ScrollController? scrollController;
  final List<T> data;
  final Color backgroundColor;
  final ItemWidgetBuilder<T>? itemBuilder;
  final IndexedItemBuilder<T>? item;
  final Widget? emptyWidget;

  const BaseListView({
    super.key,
    this.enablePullUp = false,
    this.enablePullDown = false,
    this.onRefresh,
    this.onLoading,
    this.refreshController,
    this.scrollController,
    required this.data,
    this.itemBuilder,
    this.item,
    this.backgroundColor = Colors.white,
    this.emptyWidget,
  }) : assert(itemBuilder != null || item != null, '必须提供itemBuilder或item');

  @override
  State<BaseListView<T>> createState() => _BaseListViewState<T>();
}

class _BaseListViewState<T> extends State<BaseListView<T>> {
  @override
  void dispose() {
    widget.scrollController?.dispose();
    super.dispose();
  }

  Widget _buildRefreshWrapper(Widget child) {
    return RefreshConfiguration(
      headerTriggerDistance: 10,
      footerTriggerDistance: 0,
      enableBallisticLoad: false,
      headerBuilder: () => const RefreshHeader(),
      footerBuilder: () => const LoadingFooter(),
      child: ColoredBox(
        color: widget.backgroundColor,
        child: SmartRefresher(
          physics: const BouncingScrollPhysics(),
          enablePullUp: widget.enablePullUp,
          enablePullDown: widget.enablePullDown,
          controller: widget.refreshController ?? RefreshController(),
          onRefresh: widget.onRefresh,
          onLoading: widget.onLoading,
          child: child,
        ),
      ),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    final item = widget.data[index];

    return widget.item != null
        ? widget.item!(item, index: index)
        : widget.itemBuilder!(item, index);
  }

  Widget _buildListContent() {
    if (widget.data.isEmpty && widget.emptyWidget != null) {
      return widget.emptyWidget!;
    }

    return ListView.builder(
      cacheExtent: 20,
      physics: const BouncingScrollPhysics(),
      controller: widget.scrollController,
      itemCount: widget.data.length,
      itemBuilder: _buildListItem,
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildRefreshWrapper(_buildListContent());
  }
}
